<template>
  <div id="exchange">
    <div class="head-top">
      <span>兑换</span>
    </div>
    <div class="exc_box">
      <div class="box_top">
        <div class="left" @click="clickToken('left')">
          <div>
            <!-- <img class="coinImg" :src="leftToken.select.img" alt /> -->
            <span>{{leftToken.select.symbol}}</span>
          </div>
          <img class="down_arr" src="static/img/down_arr.png" alt />
        </div>
        <!-- @click="exchang"  -->
        <img class="box_img" src="static/img/exchange_icon.png" alt />
        <div class="right" @click="clickToken('right')">
          <div>
            <!-- <img class="coinImg" :src="rightToken.select.img" alt /> -->
            <span>{{rightToken.select.symbol}}</span>
          </div>
          <img class="down_arr" src="static/img/down_arr.png" alt />
        </div>
      </div>

      <div class="box_bottom">
        <input class="out" type="number" v-model="outAmount" placeholder="转出数量" />
        <input class="in" readonly type="number" v-model="inAmount" placeholder="收到数量" />
      </div>

      <div class="box_balance" v-if="state==2">
        <!--<div>可用赎回余额:</div>-->
        <!--<div>当前允许赎回最大额度: {{rightToken.select.usableBalance*rightToken.select.rate}} {{leftToken.select.symbol}} = {{rightToken.select.usableBalance}} {{rightToken.select.symbol}}</div>-->
        <div>当前最大可兑换额度: {{rightToken.select.usableBalance}} {{rightToken.select.symbol}}</div>
      </div>
    </div>
    <div class="auth" v-if="showAuth">
      <div
        class="btn"
        @click="popupVisible=true"
        v-if="showAuth"
      >
         <img src="static/img/auth.png" alt />
          <span>去授权</span>
      </div>
      <div
        style="display: block;text-align: center;font-size:.9rem;margin: 0rem auto .6rem auto;color:red"
      >首次兑换 MDPOX 需对当前资产进行授权</div>
    </div>
    <div class="longTime" @click="clickToken('time')">
      <div class="left">
        <div class="time">质押时长：</div>
        <!-- <div style="display: inline-block;padding-left: .4rem;padding-top: .4rem;">
            <img class="coinImg" :src="leftToken.select.img" alt />
        </div>-->
        <div>{{timeVal}}</div>
      </div>
      <img class="down_arr" src="static/img/down_arr.png" style="display: inline-block;" alt />
    </div>
    <div class="btn blue" v-if="state==1" @click="showChange()">
      <img src="static/img/exchange3.png" alt />
        <span>兑换</span>
    </div>
    <div class="rate" style="margin-bottom:4rem">
      <p class="l-title">兑换汇率：1:1</p>
      <p class="l-content">授权及兑换操作通过智能合约完成，完全去中心化，需要消耗少量ETH作为矿工手续费，请确保您的钱包内有足够的ETH</p>
      <p class="l-title">兑换&质押规则：</p>
      <p
        class="l-content"
      >MDAC代币可闪兑MDPOX,比例1:1,闪兑完即锁仓，锁仓的MDPOX开始质押挖矿，挖矿的收益会以MDACX的形式在闪兑完之后就立即发放。闪兑的时候有不同时长的质押选项，到期之后可用的MDPOX可再次兑回MDAC。</p>
      <p class="sm-title">1、闪兑选项</p>
      <p class="sm-content">闪兑的选择总共7种，每种时长除释放时间不一样之外，资金利用率也不同。（资金利用率指的是该锁仓币实际产生收益的部分比例是多少）</p>
      <p class="sm-content">锁仓7天：资金利用率50%</p>
      <p class="sm-content">锁仓1个月：资金利用率60%</p>
      <p class="sm-content">锁仓3个月：资金利用率75%</p>
      <p class="sm-content">锁仓6个月：资金利用率85%</p>
      <p class="sm-content">锁仓12个月：资金利用率100%</p>

      <p class="sm-title">2、平台分红S：</p>
      <p class="sm-content">S代表平台分红，例如取0.1代表平台分红1成，</p>
      <p class="sm-content">S总共有6个比例，按照质押(即锁仓)的MDPOX数量来触发</p>
      <p class="sm-content">MDPOX <=500 ------ S=0.1</p>
      <p class="sm-content">MDPOX <=2000 ------ S=0.09</p>
      <p class="sm-content">MDPOX <=8000 ------ S=0.08</p>
      <p class="sm-content">MDPOX <=25000 ------ S=0.07</p>
      <p class="sm-content">MDPOX <=60000 ------ S=0.06</p>
      <p class="sm-content">MDPOX <=120000 ------ S=0.05</p>
      <p class="sm-title">3、质押收益率：</p>
      <p class="sm-content">质押收益率=</p>
      <p class="sm-content">持有12个月的MDPOX收益率=矿机挖矿年化收益率*资金利用率*(1-S)</p>
      <p class="sm-content">持有6个月的MDPOX收益率=矿机挖矿年化收益率*资金利用率*(1-S)*6/12</p>
      <p class="sm-content">持有3个月的MDPOX收益率=矿机挖矿年化收益率.资金利用率*(1-S)*3/12</p>
      <p class="sm-content">持有1个月的MDPOX收益率=矿机挖矿年化收益率*资金利用率*(1-S)*1/12</p>
      <p class="sm-content">持有1星期的MDPOX收益率=矿机挖矿年化收益率*资金利用率*(1-S)*1/48</p>

      <p class="sm-title">4、收益发放(MDPACX数量)：</p>
      <p class="sm-content">收益以MDACX分发(12个月内恒定按0.1usdt估值进行分红)</p>
      <p class="sm-content">发放数量=持有MDPOX数量*质押收益率/0.1</p>
    </div>

    <div class="btn blue" v-if="state==2" @click="showRedemption()">
      <img src="static/img/exchange3.png" alt />
      <span>兑换</span>
    </div>

    <mt-popup v-model="popupLeft" position="bottom" class="pop_panel">
      <div
        v-for="(item,index) in leftToken.tokenArr"
        :key="index"
        @click="selectToken('left',item,index)"
      >
        <div class="pop_item">
          <img :src="item.img" alt />
          <div class="right">
            <div class="name">{{item.symbol}}</div>
            <div class="sum">余额：{{item.sum}} {{item.balance}}</div>
          </div>
          <div class="pitchOn" v-if="item.symbol === leftToken.select.symbol">
            <img src="static/img/xz.png" alt />
          </div>
        </div>
      </div>
    </mt-popup>
    <mt-popup v-model="popupRight" position="bottom" class="pop_panel">
      <div
        v-for="(item,index) in rightToken.tokenArr"
        :key="index"
        @click="selectToken('right',item,index)"
      >
        <div class="pop_item">
          <img :src="item.img" alt />
          <div class="right">
            <div class="name">{{item.symbol}}</div>
            <div class="sum">余额：{{item.sum}} {{item.balance}}</div>
          </div>
          <div class="pitchOn" v-if="item.symbol === rightToken.select.symbol">
            <img src="static/img/xz.png" alt />
          </div>
        </div>
      </div>
    </mt-popup>

    <mt-popup v-model="timeRight" position="bottom" class="pop_panel">
      <div v-for="(item,index) in timeArr" :key="index" @click="selectToken('time',item,index)">
        <div class="pop_item">
          <div class="right" style="margin-left:1rem">
            <div class="name">{{item}}</div>
          </div>
          <div class="pitchOn" v-if="item.symbol === rightToken.select.symbol">
            <img src="static/img/xz.png" alt />
          </div>
        </div>
      </div>
    </mt-popup>

    <mt-popup
      id="enterPopul"
      v-model="popupVisible"
      position="bottom"
      style="width: 100%;padding: 0rem 0rem 4.5rem 0rem"
    >
      <h3 style="margin:.5rem 0rem;text-align: center">支付详情</h3>

      <mt-field
        label="订单信息"
        v-model="orderTitle"
        readonly
        style="width: 90%;margin: 0px auto;border-top: 1px solid rgba(0,0,0,0.1)"
      ></mt-field>
      <mt-field
        label="收款地址"
        v-model="leftToken.select.address"
        readonly
        style="width: 90%;margin: 0px auto"
      ></mt-field>
      <mt-field
        label="付款钱包"
        v-model="currentAccount.address"
        readonly
        style="width: 90%;margin: 0px auto"
      ></mt-field>
      <mt-field
        label="矿工费"
        :value="poundage+' ETH ≈ '+(poundage*currentAccount.ethPrice*global.rate).toFixed(4) +' CNY'"
        readonly
        style="width: 90%;margin: 0px auto"
      ></mt-field>
      <!--<mt-field label="金额" :value="money+' ETH'" style="width: 90%;margin: 0px auto"></mt-field>-->
      <mt-button
        type="primary"
        style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
        @click="enterPwd"
      >确认</mt-button>
    </mt-popup>

    <mt-popup
      id="enterPopulPwd"
      v-model="popupVisiblePwd"
      position="bottom"
      style="width: 100%;padding: 0rem 0rem 40% 0rem"
    >
      <h3 style="margin:.5rem 0rem;text-align: center">确认交易</h3>

      <mt-field
        label="密码"
        placeholder="请输入密码"
        type="password"
        v-model="pwd"
        style="width: 90%;margin: 0px auto"
      ></mt-field>
      <mt-button
        type="primary"
        style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
        @click="reEnterPwd"
      >确认</mt-button>
    </mt-popup>
    <foot v-show="false"  :index="index ? index : 2"></foot>
  </div>
</template>


<script>
import { Toast, Loading, Button, Popup, Notify, Dialog } from "vant";

import BigNumber from "bignumber.js";
import accountUtils from "../../service/eth/accountUtils";

import { mapGetters, mapActions } from "vuex";
import { calculateRate } from "../../service/base/supportTokens";
import axios from "axios";

import Foot from "../eth/Foot";

export default {
  components: {
    Foot,
  },
  data() {
    return {
      cloneExchangeMap: [],
      title: "兑换",
      operation: 1, //1授权 2兑换 3赎回
      state: 1,
      orderTitle: "授权操作",
      gasPrice: 0,
      poundage: 0,
      pwd: "",
      outAmount: "",
      tokenBalances: [],
      showAuth: false,
      inAmount: "",
      popupLeft: false,
      popupRight: false,
      timeRight: false,
      index: this.$route.params.index ? this.$route.params.index : 4,
      mode: 1,
      leftToken: {
        select: "",
        index: 0,
        tokenArr: [],
      },
      rightToken: {
        select: "",
        index: 0,
        tokenArr: [],
      },
      timeVal: "1星期",
      timeArr: ["1星期", "1个月", "3个月", "6个月", "12个月"],
      asynArrLeft: [],
      asynArrRight: [],
      popupVisible: false,
      popupVisiblePwd: false,
       screenHeight: document.documentElement.clientHeight, // 当前高度
      originHeight: document.documentElement.clientHeight, //默认高度，用作比较
      isOriginHeight: false, //当前高度是否仍等于默认高度
    };
  },
  computed: {
    ...mapGetters([
      "wallet",
      "accountIndex",
      "coinsList",
      "exchangeMap",
      "currentAccount",
      "messageList",
    ]),
  },
  created() {
    // Dialog.alert({
    //   title: '提示',
    //   message: '金额不够了'
    // }).then(() => {
    //   // on close
    // });
    // this.leftToken.tokenArr =[].push(mainCoin)
    // this.leftToken.select=mainCoin
    // this.rightToken.tokenArr = supportCoinArray
    // this.rightToken.select=supportCoinArray[0]

    // Notify({
    //   message: '授权交易已发出，请耐心等待打包结果，请勿重复提交',
    //   color: '#fff',
    //   background: '#4099e2',
    //   duration: 300000
    // });

    // Toast.loading({
    //   duration: 0,
    //   forbidClick: true,
    //   message: '等待打包中...'
    // });

    // setTimeout(()=>{
    //   Toast.clear()
    // },2000)

    this.cloneExchangeMap = JSON.parse(JSON.stringify(this.exchangeMap));
    this.leftToken.tokenArr = this.cloneExchangeMap[0].supportCoinArray;
    this.leftToken.select = this.cloneExchangeMap[0].supportCoinArray[0];
    this.rightToken.tokenArr = this.cloneExchangeMap;
    this.rightToken.select = this.cloneExchangeMap[0];

    // for(let i=0;i<this.supportCoinArray.length;i++){
    //   this.tokenBalances.push({
    //     symbol:this.supportCoinArray[i].symbol,
    //     balance:0
    //   })
    // }

    let _this = this;

    if (!_this.global.web3) {
      accountUtils
        .initWeb3FromPrivateKey(_this.currentAccount.priKey)
        .then(({ web3, provider, priKey, pubKey, address }) => {
          _this.global.setWeb3(web3);
          _this.global.web3.eth.getGasPrice().then((gasPrice) => {
            console.log(gasPrice);
            _this.gasPrice =
              gasPrice > 10000000000
                ? (gasPrice * 1.2).toFixed(0)
                : 10000000000;
            _this.poundage = this.convertBigNumber(
              (this.gasPrice * 60000) / Math.pow(10, 18)
            );
            console.log(_this.gasPrice);
          });
          _this.getTokenArrBalance();
        });
    } else {
      this.global.web3.eth.getGasPrice().then((gasPrice) => {
        console.log(gasPrice);
        _this.gasPrice =
          gasPrice > 10000000000 ? (gasPrice * 1.2).toFixed(0) : 10000000000;
        _this.poundage = this.convertBigNumber(
          (this.gasPrice * 60000) / Math.pow(10, 18)
        );
        console.log(_this.gasPrice);
      });
      this.getTokenArrBalance();
    }
  },
  watch: {
    screenHeight(val) {
      if (this.originHeight - val > 60) {
        //这里以防万一改了下判断形式，当屏幕高度减少了60px以上时才隐藏footer
        this.isOriginHeight = false;
      } else {
        this.isOriginHeight = true;
      }
    },
    outAmount(newval, oldval) {
      if (this.state == 1) {
        this.inAmount = calculateRate(this.leftToken.select, newval, this.state)
          ? calculateRate(this.leftToken.select, newval, this.state)
          : "";
      } else if (this.state == 2) {
        this.inAmount = calculateRate(
          this.rightToken.select,
          newval,
          this.state
        )
          ? calculateRate(this.rightToken.select, newval, this.state)
          : "";
      }
    },
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.screenHeight = document.documentElement.clientHeight;
      })();
    };
  },
  methods: {
    ...mapActions([
      "setWallet",
      "setMainCoin",
      "setSupportCoinArray",
      "setCoinsList",
      "setAccountIndex",
      "setCoinByIndex",
      "setEthBalance",
      "setEthPrice",
      "setBalance",
      "setWalletAccountByIndex",
    ]),
    accMul(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).multipliedBy(arg2).valueOf()
      );
    },
    accDiv(arg1, arg2) {
      return this.convertBigNumber(
        new BigNumber(arg1).dividedBy(arg2).valueOf()
      );
    },
    convertBigNumber: (param) => {
      let strParam = String(param);
      let flag = /e/.test(strParam);
      if (!flag) return param;

      // 指数符号 true: 正，false: 负
      let sysbol = true;
      if (/e-/.test(strParam)) {
        sysbol = false;
      }
      // 指数
      let index = Number(strParam.match(/\d+$/)[0]);
      // 基数
      let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, "");

      if (sysbol) {
        return basis.padEnd(index + 1, 0);
      } else {
        return basis.padStart(index + basis.length, 0).replace(/^0/, "0.");
      }
    },
    enterPwd() {
      if (parseFloat(this.currentAccount.eth) < this.poundage) {
        Dialog.alert({
          title: "提示",
          message: "您的Eth余额不足，不足以完成操作",
        }).then(() => {
          // on close
        });

        return;
      }
      this.popupVisible = !this.popupVisible;
      this.popupVisiblePwd = !this.popupVisiblePwd;
      // this.poundage=this.convertBigNumber(this.gasPrice * 60000 /Math.pow(10,18))
    },
    reEnterPwd() {
      let _this = this;
      if (!this.pwd) {
        _this.popupVisiblePwd = false;
        Dialog.alert({
          title: "提示",
          message: "请输入密码!",
        }).then(() => {
          // on close
        });
        return;
      } else if (this.pwd != this.currentAccount.password) {
        _this.popupVisiblePwd = false;
        Dialog.alert({
          title: "提示",
          message: "密码错误!",
        }).then(() => {
          // on close
        });
        return;
      }
      if (parseFloat(this.currentAccount.eth) < this.poundage) {
        _this.popupVisiblePwd = false;
        Dialog.alert({
          title: "提示",
          message: "您的Eth余额不足，不足以完成操作",
        }).then(() => {
          // on close
        });
        return;
      }
      this.popupVisiblePwd = !this.popupVisiblePwd;

      if (this.operation == 1) {
        this.authToken();
      } else if (this.operation == 2) {
        this.exchangeToken();
      } else if (this.operation == 3) {
        this.redemptionToken();
      }
    },
    authToken() {
      let _this = this;
      let abi = _this.leftToken.select.abi;
      let address = _this.leftToken.select.address;
      let decimals = _this.leftToken.select.decimals;
      let tokenContract = new this.global.web3.eth.Contract(abi, address);

      let isAddSend = false;
      let tran = {};
      let coin;
      for (let i = 0; i < _this.coinsList.length; i++) {
        if (_this.coinsList[i].name == _this.leftToken.select.symbol) {
          coin = _this.coinsList[i];
          if (coin.switch == false) {
            _this.coinsList[i].open = true;
            _this.setCoinsList(_this.coinsList);
          }
          break;
        }
      }

      Notify({
        message: "授权交易已发出，请耐心等待打包结果，请勿重复提交",
        color: "#fff",
        background: "#4099e2",
        duration: 600000,
      });

      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: "等待打包中...",
      });

      Promise.all([this.global.web3.eth.getGasPrice()])
        .then((data) => {
          console.log(
            _this.convertBigNumber(
              _this.accMul(1000000, Math.pow(10, decimals)).valueOf()
            )
          );
          tokenContract.methods
            .approve(
              _this.rightToken.select.address,
              _this.convertBigNumber(
                _this.accMul(1000000, Math.pow(10, decimals)).valueOf()
              )
            )
            .send({
              from: _this.currentAccount.address,
              gas: 60000,
              gasPrice: _this.gasPrice + 10000000000,
            })
            .on("transactionHash", function (hash) {})
            .on("receipt", function (receipt) {
              Toast.clear();
              Notify.clear();
              Notify({
                message: "授权成功！",
                color: "#fff",
                background: "#00C062",
                duration: 5000,
              });
              _this.pwd = "";

              _this.leftToken.select.tokenAllowance = _this.convertBigNumber(
                1000000 * Math.pow(10, decimals)
              );
              _this.showAuth = false;
            })
            .on("confirmation", function (confirmationNumber, receipt) {});
        })
        .catch((error) => {
          console.log(error);
        });
    },
    showChange() {
      console.log(this.popupVisible);

      if (!this.inAmount) {
        Dialog.alert({
          title: "提示",
          message: "请输入兑换额度!",
        }).then(() => {
          // on close
        });
        return;
      }

      if (this.state == 1 && this.leftToken.select.tokenAllowance == 0) {
        Dialog.alert({
          title: "提示",
          message: "请先完成授权操作!",
        }).then(() => {
          // on close
        });
        return;
      }

      if (
        this.leftToken.select.symbol == "DFP" &&
        this.leftToken.select.balance == this.outAmount
      ) {
        Dialog.alert({
          title: "提示",
          message:
            "DFP无法全部兑换，请在您的钱包内留一个最小余额，比如0.00000001",
        }).then(() => {
          // on close
        });

        return;
      } else if (this.leftToken.select.balance < this.outAmount) {
        Dialog.alert({
          title: "提示",
          message: "您的" + this.leftToken.select.symbol + "余额不足！",
        }).then(() => {
          // on close
        });

        return;
      } else {
        this.popupVisible = !this.popupVisible;
        this.orderTitle = "兑换操作";
        this.poundage = this.convertBigNumber(
          (this.gasPrice * 400000) / Math.pow(10, 18)
        );
        this.operation = 2;
      }
    },
    exchangeToken() {
      let _this = this;

      let abi = _this.rightToken.select.abi;
      let mainAddr = _this.rightToken.select.address;
      let mainCont = new _this.global.web3.eth.Contract(abi, mainAddr);
      console.log(abi);
      let isAddSend = false;
      let tran = {};
      let coin;
      for (let i = 0; i < _this.coinsList.length; i++) {
        if (_this.coinsList[i].name == _this.leftToken.select.symbol) {
          coin = _this.coinsList[i];
          if (coin.switch == false) {
            _this.coinsList[i].open = true;
            _this.setCoinsList(_this.coinsList);
          }
          break;
        }
      }

      Toast.loading({
        duration: 0,
        forbidClick: true,
      });

      console.log(
        this.convertBigNumber(
          parseFloat(this.outAmount) *
            Math.pow(10, this.leftToken.select.decimals)
        ) + ""
      );
      console.log(_this.gasPrice);
      mainCont.methods
        .exchange(this.outAmount, this.mode)
        .send({
          from: _this.currentAccount.address,
          value: 0,
          gas: 400000,
          gasPrice: _this.gasPrice,
          data: "",
        })
        .on("transactionHash", function (hash) {
          console.log("交易hash:" + hash);
          tran = {
            name: _this.leftToken.select.symbol,
            fromAddress: _this.currentAccount.address,
            toAddress: mainAddr,
            img: "static/img/to2.png",
            error: false,
            get: false,
            txhash: hash,
            blockNumber: "",
            decimals: _this.leftToken.select.decimals,
            blockHash: "",
            date: "1秒前",
            timeStamp: (new Date().getTime() + "").substring(0, 10),
            value:
              _this.outAmount * Math.pow(10, _this.leftToken.select.decimals),
            input: "",
            pending: true,
          };

          Toast.clear();
          if (_this.leftToken.select.symbol == "ETH") {
            _this.currentAccount.transactionList.push(tran);
            _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
            _this.setWalletAccountByIndex(
              this.currentAccount,
              _this.accountIndex
            );
            Toast.clear();
            setTimeout(() => {
              _this.$router.replace({
                name: "Transaction",
                params: { symbol: "ETH", dontRefresh: true },
              });
            }, 200);
          } else {
            if (!_this.currentAccount.coins[_this.leftToken.select.symbol])
              _this.currentAccount.coins[_this.leftToken.select.symbol] = [];
            _this.currentAccount.coins[_this.leftToken.select.symbol].push(
              tran
            );
            _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
            _this.currentAccount.currentCoin = coin;
            _this.setWalletAccountByIndex(
              this.currentAccount,
              _this.accountIndex
            );

            setTimeout(() => {
              _this.$router.replace({
                name: "TransactionERC",
                params: { symbol: coin.name, coin: coin, dontRefresh: true },
              });
            }, 200);
          }
        })
        .on("receipt", function (receipt) {
          if (!isAddSend) {
            // console.log(receipt)
            tran.gasMoney = _this.global.web3.utils.fromWei(
              parseInt(receipt.gasUsed) * 1000000000 + "",
              "ether"
            );
            tran.blockNumber = receipt.blockNumber;
            tran.blockHash = receipt.blockHash;
            tran.pending = false;

            _this.currentAccount.ethBalance -= val;
            isAddSend = true;
            let message = {
              message:
                "交易通知: " +
                _this.leftToken.select.symbol +
                "兑换 " +
                _this.rightToken.select.symbol +
                " 成功",
              type: "to",
              from: _this.currentAccount.address,
              to: mainAddr,
              timeStamp: new Date().getTime(),
              isRead: false,
              tran: tran,
            };
            _this.messageList.push(message);
          }

          Toast.clear();
        });
    },

    showRedemption() {
      console.log(this.leftToken);
      console.log(this.rightToken);
      if (this.outAmount > this.leftToken.select.balance) {
        Dialog.alert({
          title: "提示",
          message: "您的" + this.leftToken.select.symbol + "余额不足！",
        }).then(() => {
          // on close
        });

        return;
      } else {
        console.log("足够");
        this.popupVisible = !this.popupVisible;
        this.orderTitle = "兑换操作";
        this.poundage = this.convertBigNumber(
          (this.gasPrice * 100000) / Math.pow(10, 18)
        );
        this.operation = 3;
      }
    },
    redemptionToken() {
      let _this = this;
      // '472501591B92573CD2758F22DF9CEA22A303180B04C9CA2E7053147981C6C132'
      let tokenAddress = _this.rightToken.select.address;
      let abi = _this.leftToken.select.abi;
      let mainAddr = _this.leftToken.select.address;
      let mainCont = new _this.global.web3.eth.Contract(abi, mainAddr);

      let isAddSend = false;
      let tran = {};
      let coin;
      for (let i = 0; i < _this.coinsList.length; i++) {
        if (_this.coinsList[i].name == _this.leftToken.select.symbol) {
          coin = _this.coinsList[i];
          if (coin.switch == false) {
            _this.coinsList[i].open = true;
            _this.setCoinsList(_this.coinsList);
          }
          break;
        }
      }

      Toast.loading({
        duration: 0,
        forbidClick: true,
      });
      console.log(tokenAddress);
      console.log(
        this.convertBigNumber(
          parseFloat(this.outAmount) *
            Math.pow(10, this.leftToken.select.decimals)
        )
      );
      console.log(_this.gasPrice);
      mainCont.methods
        .redemptionToken(
          tokenAddress,
          parseFloat(this.outAmount) *
            Math.pow(10, this.leftToken.select.decimals) +
            ""
        )
        .send({
          from: _this.currentAccount.address,
          value: 0,
          gas: 300000,
          gasPrice: _this.gasPrice,
          data: "",
        })
        .on("transactionHash", function (hash) {
          console.log("交易hash:" + hash);
          tran = {
            name: _this.leftToken.select.symbol,
            fromAddress: _this.currentAccount.address,
            toAddress: mainAddr,
            img: "static/img/to2.png",
            error: false,
            get: false,
            txhash: hash,
            blockNumber: "",
            decimals: _this.leftToken.select.decimals,
            blockHash: "",
            date: "1秒前",
            timeStamp: (new Date().getTime() + "").substring(0, 10),
            value:
              _this.outAmount * Math.pow(10, _this.leftToken.select.decimals),
            input: "",
            pending: true,
          };

          Toast.clear();
          if (_this.leftToken.select.symbol == "ETH") {
            _this.currentAccount.transactionList.push(tran);
            _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
            _this.setWalletAccountByIndex(
              this.currentAccount,
              _this.accountIndex
            );
            Toast.clear();
            setTimeout(() => {
              _this.$router.replace({
                name: "Transaction",
                params: { symbol: "ETH", dontRefresh: true },
              });
            }, 200);
          } else {
            if (!_this.currentAccount.coins[_this.leftToken.select.symbol])
              _this.currentAccount.coins[_this.leftToken.select.symbol] = [];
            _this.currentAccount.coins[_this.leftToken.select.symbol].push(
              tran
            );
            _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
            _this.currentAccount.currentCoin = coin;
            _this.setWalletAccountByIndex(
              this.currentAccount,
              _this.accountIndex
            );

            setTimeout(() => {
              _this.$router.replace({
                name: "TransactionERC",
                params: { symbol: coin.name, coin: coin, dontRefresh: true },
              });
            }, 200);
          }
        })
        .on("receipt", function (receipt) {
          if (!isAddSend) {
            // console.log(receipt)
            tran.gasMoney = _this.global.web3.utils.fromWei(
              parseInt(receipt.gasUsed) * 1000000000 + "",
              "ether"
            );
            tran.blockNumber = receipt.blockNumber;
            tran.blockHash = receipt.blockHash;
            tran.pending = false;

            _this.currentAccount.ethBalance -= val;
            isAddSend = true;
            let message = {
              message:
                "交易通知: " +
                _this.leftToken.select.symbol +
                "兑换 " +
                _this.rightToken.select.symbol +
                " 成功",
              type: "to",
              from: _this.currentAccount.address,
              to: mainAddr,
              timeStamp: new Date().getTime(),
              isRead: false,
              tran: tran,
            };
            _this.messageList.push(message);
          }

          Toast.clear();
        });
    },
    getTokenArrBalance() {
      let _this = this;

      for (let z = 0; z < _this.cloneExchangeMap.length; z++) {
        let abi = _this.cloneExchangeMap[z].abi;
        let mainAddr = _this.cloneExchangeMap[z].address;
        let mainCont = new _this.global.web3.eth.Contract(abi, mainAddr);

        //获取账户主代币余额
        Promise.all([
          mainCont.methods.balanceOf(this.currentAccount.address).call(),
        ])
          .then((data) => {
            if (_this.state == 1) {
              let mainBalance = _this.accDiv(
                parseFloat(data[0]),
                Math.pow(10, parseFloat(_this.cloneExchangeMap[z].decimals))
              );
              _this.cloneExchangeMap[z].balance = mainBalance;
              _this.rightToken.select.balance = mainBalance;
              _this.rightToken.balance = mainBalance;
            }
          })
          .catch((error) => {
            console.log(error);
          });

        let arr = [].concat(_this.cloneExchangeMap[z].supportCoinArray);
        for (let i = 0; i < arr.length; i++) {
          let abi = arr[i].abi;
          let address = arr[i].address;
          let decimals = arr[i].decimals;
          // let {abi,address}=require('../../service/base/supportCoin/'+arr[i].symbol);
          let cont = new _this.global.web3.eth.Contract(abi, address);

          Promise.all([
            cont.methods.balanceOf(_this.currentAccount.address).call(),
            cont.methods
              .allowance(_this.currentAccount.address, mainAddr)
              .call(),
            cont.methods.balanceOf(mainAddr).call(),
          ])
            .then((data) => {
              if (parseFloat(data[1]) == 0) {
                arr[i].auth = false;
              } else {
                arr[i].auth = true;
              }
              _this.cloneExchangeMap[z].supportCoinArray[
                i
              ].balance = _this.accDiv(
                parseFloat(data[0]),
                Math.pow(10, decimals)
              );
              _this.cloneExchangeMap[z].supportCoinArray[
                i
              ].tokenAllowance = _this.accDiv(
                parseFloat(data[1]),
                Math.pow(10, decimals)
              );
              _this.cloneExchangeMap[z].supportCoinArray[
                i
              ].usableBalance = _this.accDiv(
                parseFloat(data[2]),
                Math.pow(10, decimals)
              );

              arr[i].balance = _this.accDiv(
                parseFloat(data[0]),
                Math.pow(10, decimals)
              );
              arr[i].tokenAllowance = _this.accDiv(
                parseFloat(data[1]),
                Math.pow(10, decimals)
              );
              arr[i].usableBalance = _this.accDiv(
                parseFloat(data[2]),
                Math.pow(10, decimals)
              );
              if (_this.state == 1 && i == 0) {
                _this.leftToken.tokenArr = arr;
              }

              if (
                _this.cloneExchangeMap[0].supportCoinArray[0].tokenAllowance ==
                0
              ) {
                _this.showAuth = true;
              }

              console.log(_this.leftToken);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      }
    },
    exchang() {
      //return

      if (this.state == 1) {
        this.state = 2;
        this.showAuth = false;
        //  this.title='赎回'
      } else {
        this.state = 1;
        console.log(this.leftToken);
        if (this.rightToken.select.tokenAllowance == 0) {
          this.showAuth = true;
        }
        // this.title='兑换'
      }
      this.outAmount = "";
      this.inAmount = "";
      let box = this.leftToken;
      this.leftToken = this.rightToken;
      this.rightToken = box;
    },
    clickToken(is) {
      if (is === "left") {
        this.popupLeft = true;
      } else if (is === "right") {
        this.popupRight = true;
      } else if (is === "time") {
        this.timeRight = true;
      }
    },
    selectToken(is, token, index) {
      this.mode = index + 1;
      if (is === "left") {
        this.popupLeft = false;
        this.leftToken.select = token;

        if (token.tokenAllowance == 0) {
          this.showAuth = true;
        } else {
          this.showAuth = false;
        }
      } else if (is === "right") {
        this.popupRight = false;
        this.rightToken.select = token;
        this.leftToken.tokenArr = token.supportCoinArray;
        this.leftToken.select = token.supportCoinArray[0];
      } else if (is === "time") {
        this.timeRight = false;
        this.timeVal = token;
      }
      this.inAmount = "";

      if (this.state == 1) {
        this.inAmount = calculateRate(
          this.leftToken.select,
          this.outAmount,
          this.state
        )
          ? calculateRate(this.leftToken.select, this.outAmount, this.state)
          : "";
      } else if (this.state == 2) {
        this.inAmount = calculateRate(
          this.rightToken.select,
          this.outAmount,
          this.state
        )
          ? calculateRate(this.rightToken.select, this.outAmount, this.state)
          : "";
      }
    },
    convertBigNumber: (param) => {
      let strParam = String(param);
      let flag = /e/.test(strParam);
      if (!flag) return param;

      // 指数符号 true: 正，false: 负
      let sysbol = true;
      if (/e-/.test(strParam)) {
        sysbol = false;
      }
      // 指数
      let index = Number(strParam.match(/\d+$/)[0]);
      // 基数
      let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, "");

      if (sysbol) {
        return basis.padEnd(index + 1, 0);
      } else {
        return basis.padStart(index + basis.length, 0).replace(/^0/, "0.");
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/css/exchange.less");
.van-notify {
  padding: 4% 15px;
}
.van-notify,
.van-toast {
  font-size: 0.95rem;
}

.btnTit {
  display: block;
  text-align: center;
  font-size: 0.9rem;
  margin: 0rem auto 0.6rem auto;
}

.btn {
  margin: 1.3rem auto;
  width: 11.5625rem;
  height: 3.4375rem;
  background: #61ADCA ;
  box-shadow: 0px 6px 7px 0px rgba(28, 49, 220, 0.31);
  border-radius: 0.1875rem;
  display: flex;
  align-items: center;
  justify-content: center;
  &.blue {
    background: rgba(50, 70, 223, 1);
  }
  img {
    width: 1.3125rem;
    margin-right: .375rem;
  }
  span {
    font-size: 17px;
    color: #fff;
  }
}
</style>

